package com.example.client;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import entity.Contacter;

public class MonitorSMS extends AppCompatActivity {
    SmsGetserver observer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_monitor_sms);

        // 给指定Uri注册内容观察器，一旦发生数据变化，就触发观察器的onChange方法
        Uri uri = Uri.parse("content://sms");
        observer = new SmsGetserver(this);
        getContentResolver().registerContentObserver(uri,true,observer);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getContentResolver().unregisterContentObserver(observer);
    }

    // 观察者
    private static class SmsGetserver extends ContentObserver {
        private Context mContext;
        public SmsGetserver(Context context) {
            super(new Handler(Looper.getMainLooper()));
            this.mContext = context;
        }

        @Override
        public void onChange(boolean selfChange,Uri uri) {
            super.onChange(selfChange, uri);
            if (uri == null){
                return;
            }
            if (uri.toString().contains("content://sms/raw") ||
            uri.toString().equals("content://sms")){
                return;
            }
            Cursor cu = mContext.getContentResolver().query(uri, new String[]{"address", "body", "date"}, null, null, "date desc");
            if (cu.moveToNext()){
                // 短信发送的号码
                @SuppressLint("Range") String sender = cu.getString(cu.getColumnIndex("address"));
                // 短信内容
                @SuppressLint("Range") String content = cu.getString(cu.getColumnIndex("body"));

                Log.e("TAG", "onChange: "+ sender+content );
            }
            cu.close();

        }
    }
}